import Cookies from "js-cookie";

// token存储在cookie中，key为{tokenKey}
const tokenKey = "token";

/**
 * 获取token
 */
export function getToken() {
    return Cookies.get(tokenKey);
}

/**
 * 设置token
 * @param {string} token 
 */
export function setToken(token) {
    try {
        const payload = parseToken(token);
        // const exp = (payload.exp - Date.now())
        // 10天有效
        Cookies.set(tokenKey, token, { expires: 10 });
        Cookies.set("avatar", payload.avatar);
        Cookies.set("name", payload.username);
        Cookies.set("uid", payload.uid);
    } catch (error) {
    }
}

/**
 * 解析token
 *  - 后端返回的token是经过安全的base64编码的
 *  - 安全的base64编码是把所有的'+'变'-'，'/'变'_'
 *  - 所以前端解码要反着来
 * jwtToken
 *  - Header（头部）
 *  - Payload（负载）携带用户信息
 *  - Signature（签名
 * @param {string} token 后端返回的jwtToken
 */
export function parseToken(token) {
    let base64 = token.split(".")[1];
    if (!base64 || typeof base64 !== "string") {
        console.log(base64);
        return null;
    }
    base64 = base64.replace(/-/g, '+').replace(/_/, '/');
    return JSON.parse(window.atob(base64));
}

/**
 * t清除oken
 */
export function removeToken() {
    Cookies.remove(tokenKey);
    Cookies.remove("avatar");
    Cookies.remove("name");
    Cookies.remove("uid");
}

export function getUserInfo() {
    return {
        avatar: Cookies.get("avatar"),
        name: Cookies.get("name"),
        uid: Cookies.get("uid")
    }
}